package com.autonavi.yunda.yunji.core.utils.diling;

/**
 * @author cizhong.wcs
 * @date 2023/4/27 10:28
 */

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * token生成工具
 */
public class GenerateTokenPreUtils {
    public static String getTokenStringAb(Map<String, String> requestData) {
        StringBuilder sb = new StringBuilder();
        Map<String, String> map = new TreeMap<>();
        for (Map.Entry<String, String> entry : requestData.entrySet()) {
            if ("token".equals(entry.getKey()) || "gsid".equals(entry.getKey().toLowerCase())) {
                continue;
            }
            //使用treemap对key进行排序
            map.put(entry.getKey(), entry.getValue());
        }
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            //获取Value，拼接生成token的字符串
            sb.append(iterator.next().getValue());
            sb.append(";");
        }
        return sb.toString();
    }

    /**
     * @param pk          私钥
     * @param requestData 参数结合
     * @return
     */
    public static String checkTokenAba(String pk, Map<String, String> requestData) {
        String queryString = getTokenStringAb(requestData);
        queryString += pk;
        return GenerateTokenCoreUtils.getGenerateMD5Token(queryString);
    }

    public static void main(String[] args) {

        String url = "http://localhost:80/abapi/query?apiid=**&type=4&typeInfo=113.32213 23.132773,113.321782 23.132439,113.32188 23.132299,113.321899 23.131774,113.321765 23.131684,113.322049 23.131418,113.322194 23.131529,113.323124 23.131492,113.323235 23.131418,113.323491 23.131694,113.323486 23.132426,113.323003 23.132881,113.322131 23.132894,113.32213 23.132773&timeType=day&locType=day&month=202009&appname=*******&key=******&timestamp=1602838782&token=65a0a193ec37eb3f0e852241701a8ad2";

        String secretKey = "******";
        System.out.println(checkTokenAba(secretKey, getParamsFromUrl(url)));

        ;
    }

    public static Map<String, String> getParamsFromUrl(String url) {
        int index = url.indexOf("?");
        String paramsString = url.substring(index + 1);
        String[] paramsList = paramsString.split("&");
        Map<String, String> paramsMap = new HashMap<>(16);
        for (String paramKeyAndValue : paramsList) {
            paramsMap.put(paramKeyAndValue.split("=")[0], paramKeyAndValue.split("=")[1]);
        }
        return paramsMap;
    }


}